package tgc.edu.library.web.controller;

import java.util.HashSet;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import tgc.edu.library.custom.CommonController;
import tgc.edu.library.entity.Reader;
import tgc.edu.library.entity.SysUser;
import tgc.edu.library.security.UserUtils;
import tgc.edu.library.service.ReaderService;
import tgc.edu.library.web.form.ReaderForm;

@Controller
@RequestMapping(value="/reader")
public class ReaderController extends CommonController<Reader, Integer, ReaderForm>{
	@Autowired
	private UserUtils user;
	@Autowired
	private ReaderService readerService;
	
	@RequestMapping(value="/readerAll")
	public Object readerAll(ModelMap map) {
		SysUser user2 = user.getUser();
		Reader reader = readerService.findById(user2.getId());
		map.put("reader", reader);
		return "user/readerAll";
	}
	
	@Override
	public Specification<Reader> buildSpec(ReaderForm form) {
		Specification<Reader> specification=new Specification<Reader>() {

			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<Reader> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				String search = form.getSearch();
				if(StringUtils.hasText(search)) {
					Predicate username = cb.like(root.get("username"), "%"+search+"%");
					Predicate name = cb.like(root.get("name"), "%"+search+"%");
					Predicate email = cb.like(root.get("email"), "%"+search+"%");
					Predicate phone = cb.like(root.get("phone"), "%"+search+"%");
					Predicate or = cb.or(username,name, email,phone);
					rules.add(or);
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return specification;
	}
	
}
